package cn.takovh.zpl.bean;

import org.dom4j.Element;

import java.util.Iterator;
import java.util.List;

public class Smil implements ElementBean {
    private Head head;
    private Body body;

    public Smil() {
    }

    public Smil(Head head, Body body) {
        this.head = head;
        this.body = body;
    }

    public Smil(String title, List<Media> mediaList) {
        Integer totalDuration = mediaList.stream().map(Media::getDuration).reduce(0, Integer::sum);
        this.head = new Head(title, mediaList.size(), totalDuration);
        this.body = new Body(mediaList);
    }

    public Head getHead() {
        return head;
    }

    public void setHead(Head head) {
        this.head = head;
    }

    public Body getBody() {
        return body;
    }

    public void setBody(Body body) {
        this.body = body;
    }

    @Override
    public void getElement(Element root) {
        Element c1 = root.addElement("head");
        head.getElement(c1);
        Element c2 = root.addElement("body");
        body.getElement(c2);
    }

    @Override
    public void parseElement(Element root) {
        this.head = new Head();
        this.body = new Body();

        for (Iterator<Element> it = root.elementIterator(); it.hasNext(); ) {
            Element element = it.next();
            String name = element.getName();
            switch (name) {
                case "head":
                    this.head.parseElement(element);
                    break;
                case "body":
                    this.body.parseElement(element);
                    break;
                default:
                    throw new IllegalArgumentException(name);
            }
        }
    }
}
